package com.atstudying.mall.order.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author Mr.zhneg
 * @create 2020-11-21-21:29
 */
//通过feign调用的源码我们知道，feign远程调用的时候会丢失请求头
@Configuration
public class MallFeignConfig {

    @Bean("RequestContextHolder")
    public RequestInterceptor requestInterceptor(){

        return new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate requestTemplate) {
                System.out.println("拦截器的线程。。。"+Thread.currentThread().getId());

                //可以使用RequestContextHolder拿到刚进来的这个请求的数据（http://order.mall.com/toTrade）
                ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
               if (requestAttributes!=null){
                   HttpServletRequest request = requestAttributes.getRequest();
                   if (request!=null){
                       //同步请求头数据，cookie，为了发送到cart，让他知道order发送了cookie给cart，请求头不会丢失
                       String cookie = request.getHeader("Cookie");
                       //给新请求同步了老请求的cookie
                       requestTemplate.header("Cookie",cookie);
                       System.out.println("feign远程之前先进行RequestInterceptor.apply");

                   }
               }

            }
        };
    }
}
